import Vue from "vue";
import VueRouter from "vue-router";
import routes from "@/router/routers";
import NProgress from "nprogress";
import "../../node_modules/nprogress/nprogress.css";
import Stores from "@/utils/store";
import { TOKEN_key } from "@/utils/constant";
NProgress.configure({
  easing: "ease-in-out",
  speed: 300,
  trickeSpeed: 300,
});
//注册
Vue.use(VueRouter);
// 解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;

// push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};

//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject);
  return originalReplace.call(this, location).catch((err) => err);
};

const router = new VueRouter({
  mode: "hash",
  routes,
});
// 动态设置路由规则
//定义一个变量
let menus = null;

router.beforeEach(async (to, from, next) => {
  NProgress.start()

  // console.log(Vue.prototype.$api);
  // Object.defineProperty(Vue.prototype, "$api", {
  //   enumerable: true,
  //   writable: true,
  // });
  if (to.path == "/home") {
    next()
  } else {
    if (Stores.getStore(TOKEN_key)) {
      if (!menus) {
        const result = await Vue.prototype.$api.user.getmenu({
          userTel: "15820903220",
        });
        console.log("router", result.data.menuList);
        menus = result.data.menuList;
        for (let i = 0; i < menus.length; i++) {
          let routeObj = menus[i].children;
          console.log("luyou",routeObj);
          for (let j = 0; j < routeObj.length; j++) {
            let routeobj = routeObj[j];
            console.log("1", routeobj);
            // console.log(`/main${routeobj.href}`);
            // console.log(`@/views/lists${routeobj.href}.vue`);
            // console.log(`/main${routeobj.href}`);
            router.addRoute("main", {
              path: `${routeobj.beiyong2}`,
              component: () => import(`@/views${routeobj.href}.vue`),
              meta:{
                name:routeobj.beiyong2
              }
            });
          }
          next({ path: to.path })
        }
      }
      next()
    } else {
      Vue.prototype.$message.warning("您还没有登录请先登录")
      next("/home")
    }
  }
  console.log(to, "kkk");

  console.log("r", router.getRoutes());

});
router.afterEach((to, from) => {
  NProgress.done()
})
export default router;